// pages/detail/detail.jsgf  
var common = require("../../utils/public.js") //引入public.js脚本
const api = require('../../utils/api.js')
var time = require("../../utils/time.js");
import Wxml2Canvas from '../../utils/Wxml2Canvas/index';
const app = getApp();
Page({
  /** 
   * 页面的初始数据
   */
  data: {
    type: '',
    isShare: false,
    // bottom:40,
    // 结束时间 
    minute: '00',
    hour: '00',
    second: '00',
    cityNumber: {}, //城市电话
    phoneNumber: {}, //经理电话
    opacity: 0,
    //评论列表
    conmentList: [],
    //商品详情
    goodsDetails: [],
    //商品信息
    goodsMess: '',
    //轮播图
    swiperImage: [],
    // 详情图
    detailImage: [],
    //推荐商品
    goodsRecommend: [],
    //详情id
    goodsDetailsIds: "",
    //库存
    goodsStock: "",
    //
    getFraction: "",
    index: 0,
    zzindex: 0,
    goodsId: 0,
    isShow: false,
    login: true,
    shopindex: "",
    shopId: "",
    masking: 'masking',
    current: 0,
    // 轮播end
    toView: 'productBox',
    navArray: [{
      name: '商品',
      hash: 'productBox'
    }, {
      name: '详情',
      hash: 'infoBox'
    }, {
      name: '推荐',
      hash: 'recommendBox'
    }],
    // 限时抢购
    limited_list: [],
    showAdd: false,
    showNum: true,
    // 购物车数量
    num: [],
    collect: null,
    shopNumber: "",
    // 商品id
    id: "",
    goodsStock: "",
    allNum: "",

    goodsPic: '',
    shareImg: '',
    imgs: [],
    fromShare: '',
    //数量 
    inputNum: '',
    //购物车原有数量 
    inputNum1: '',
    //限时秒杀
    isSeckill: true,
    //满减活动
    isReduction: true,
    // rookiePrice: "", 
    // 1是新人
    isNewcomer: null,
    newType: null,
    // 是否可点击购物车
    isBindtap: true,
    // 是否是会员
    vipFlag: Number(wx.getStorageSync("vipFlag"))
  },
  //显示优惠活动弹出框
  openAct: common.throttleFunc(function (e) {
    this.setData({
      showModalStatus: 'on',
      actStatus: 'on'
    })
  }),
  //隐藏弹出框
  hideModal: common.throttleFunc(function (e) {
    this.setData({
      showModalStatus: '',
      desStatus: '',
      actStatus: ''
    })
  }),

  enlargeImg: function (event) {
    var src = event.currentTarget.dataset.src; //获取data-src 
    var imgList = event.currentTarget.dataset.list; //获取data-list 
    var arr = []
    imgList.forEach(function (v) {
      arr.push(v.url)
    })
    //图片预览 
    wx.previewImage({
      current: src, // 当前显示图片的http链接 
      urls: arr // 需要预览的图片http链接列表 
    })
  },
  loading() {
    let {
      newType,
      isNewcomer
    } = this.data;
    if (newType == "new") {
      if (isNewcomer != 1) {
        wx.showToast({
          title: '您不是新人!',
          icon: 'none',
        });
      }
    } else if (newType == "vip") {
      if (wx.getStorageSync("vipFlag") == 0) {
        wx.showToast({
          title: '您不是vip!',
          icon: 'none',
        });
      }
    }
  },
  //添加购物车 隐藏样式
  addStop: function (e) {
    let that = this
    // 访问接口更新数据 
    let index = that.data.index;
    let num = that.data.num;
    let cityId = wx.getStorageSync('cityId')
    let userInfoId = wx.getStorageSync('openId')
    let goodsName = that.data.goodsMess.name
    let goodsDetailsId = that.data.goodsId
    let price = that.data.goodsMess.goodsDetailsEntityList[index].price
    let totalPrice = that.data.goodsMess.goodsDetailsEntityList[index].priceVip
    // 起送数量
    let startNum = Number(that.data.goodsMess.goodsDetailsEntityList[index].startNum)
    let new_amount = startNum;
    // 价格
    if (that.data.newType != "new") {
      if (that.data.goodsMess.goodsDetailsEntityList[index].activitySeckillId == null) {
        if (wx.getStorageSync("vipFlag") == 1) {
          price = that.data.goodsMess.goodsDetailsEntityList[index].salesPriceVip
          // totalPrice = price * new_amount
        } else {
          price = that.data.goodsMess.goodsDetailsEntityList[index].salesPrice
          // totalPrice = price * new_amount
        }
      } else { //有活动
        price = that.data.goodsMess.goodsDetailsEntityList[index].seckillPrice
        // totalPrice = price * new_amount
      }
    } else {
      price = that.data.goodsMess.goodsDetailsEntityList[index].rookiePrice
    }
    totalPrice = price * new_amount
    api.set_amount({
      cityId,
      userInfoId,
      goodsName,
      goodsDetailsId,
      amount: new_amount,
      price,
      totalPrice
    }).then(res => {
      if (res.result) {
        num[index].amount = new_amount
        that.setData({
          shopNumber: res.data,
          num
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },
  tapType: function (e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let {
      goodsStock,
      goodsMess
    } = that.data;
    let goodsList = goodsMess.goodsDetailsEntityList
    goodsList.forEach((v, i) => {
      if (index == i) {
        let allNum = Math.floor(goodsStock / v.spec)
        that.setData({
          allNum,
        })
        // 限时秒杀
        if (this.data.newType != "new") {
          if (v.activitySeckillId != null) { //有限时秒杀
            that.setData({
              isSeckill: false
            })
            if (v.seckillEndDate > Date.now()) { //计时器
              this.startTimer(v.seckillEndDate);
            }
          }
        }
        // 新人价格
        if (that.data.newType == "new" && that.data.isNewcomer != 1) {
          this.setData({
            isBindtap: false
          })
        }
      }
    })
    that.setData({
      goodsId: e.currentTarget.dataset.id,
      index: e.currentTarget.dataset.index,
      zzindex: e.currentTarget.dataset.index
    })
  },
  // 锚点定位
  toViewClick: common.throttleFunc(function (e) {
    this.setData({
      toView: e.target.dataset.hash
    })
  }),

  // 自定义轮播indicator-dots样式
  swiperChange: function (e) {
    var that = this;
    if (e.detail.source == 'touch' || e.detail.source == 'autoplay') {
      that.setData({
        current: e.detail.current
      })
    }
  },

  // 跳转评价列表页面
  toConmentList: common.throttleFunc(function (e) {

    let that = this
    wx.navigateTo({
      url: '/pages/conment/conment?id=' + this.data.id,
    })
  }),
  // 首页打电话
  callGetPhone: function () {
    wx.navigateTo({
      url: '/pages/kefu/kefu',
    })
  },
  //显示商品描述弹出框
  openDes: common.throttleFunc(function (e) {
    this.setData({
      showModalStatus: 'on',
      desStatus: 'on'
    })
  }),
  // 返回上一层
  onBack: function () {
    if (this.data.fromShare === 'true' || app.globalData.scene == 1007 || app.globalData.scene == 1008) {
      wx.switchTab({
        url: '/pages/index/index'
      })
    } else {
      wx.navigateBack()
    }
  },
  //显示优惠活动弹出框
  openAct: common.throttleFunc(function (e) {
    this.setData({
      showModalStatus: 'on',
      actStatus: 'on'
    })
  }),
  //隐藏弹出框
  hideModal: common.throttleFunc(function (e) {
    this.setData({
      showModalStatus: '',
      desStatus: '',
      actStatus: ''
    })
  }),
  // 滚动时顶部nav高亮显示
  handelScroll: function (e) {
    let that = this;
    let scrollTop = e.detail.scrollTop;
    that.setData({
      scrollTop,
    })
    that.setOpacity(scrollTop, 200)
  },
  // 透明度方法
  setOpacity: function (scrollTop, maxTop) {
    var opacity = 0,
      that = this;
    if (scrollTop <= maxTop) {
      opacity = scrollTop / maxTop
    } else {
      opacity = 1
    }
    that.setData({
      opacity: opacity
    })
  },
  // 倒计时
  startTimer(seckillEndDate) {
    let now = Date.now()
    let hour = time.formatTimeTwo(seckillEndDate - now, 'h') - 8 + (time.formatTimeTwo(seckillEndDate - now, 'D') - 1) * 24
    this.setData({
      hour,
      minute: time.formatTimeTwo(seckillEndDate - now, 'm'),
      second: time.formatTimeTwo(seckillEndDate - now, 's'),
    })
    this.timer = setInterval(() => {
      let now = Date.now()
      this.setData({
        hour,
        minute: time.formatTimeTwo(seckillEndDate - now, 'm'),
        second: time.formatTimeTwo(seckillEndDate - now, 's'),
        // numTime: this.data.payovertime - now
      })

      if (seckillEndDate - Date.now() >= 0 && seckillEndDate - Date.now() <= 1000) {
        clearInterval(this.timer)
        this.timer = null
        // this.back1()
      }
    }, 1000)
  },
  onLoad: function (options) {
    //分享进入 
    let type = wx.getStorageSync("type")
    let token = wx.getStorageSync('token')
    let codeNum = wx.getStorageSync('codeNum')
    // if (!token) {
    //   if(type!=2 || (type!=1 && codeNum!=99)){
    //     wx.switchTab({
    //       url: '/pages/index/index',
    //     }) 
    //   }
    // }
    // type=1,商铺，=2 个人,
    if ((type == 1 && codeNum == 104) || !token) {
      wx.switchTab({
        url: '/pages/index/index',
      })
    }
    // 非分享进入
    wx.hideShareMenu({})
    let {
      cityId,
      id,
      userId,
      fromShare,
      shopid
    } = options
    let that = this;
    this.setData({
      fromShare,
      goodsId: shopid,
      shopId: shopid,
      cityId,
      userId,
      id,
      newType: options.types,
      // bottom: app.globalData.isFullSucreen ? '40' : '10',
      type,
    })
    wx.getSystemInfo({
      success: function (res) {
        let clientHeight = res.windowHeight;
        let clientWidth = res.windowWidth;
        let ratio = 750 / clientWidth;
        let height = clientHeight * ratio;
        that.setData({
          autoHeight: height - 112,
          id: options.id,
          barHeight: res.statusBarHeight,
          iconTop: res.statusBarHeight + 60,
          // shopindex,
        });
      }
    })
    //获取评论
    api.conmentList({
      id: options.id,
      page: {
        size: 3,
        isStartPage: false
      }
    }).then(res => {

      if (res.result == true) {
        that.setData({
          conmentList: res.object.records,
          getFraction: res.body.getFraction
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
    // 打电话（城市电话  客户经理电话）-----------------------
    api.phoneList({
      id: wx.getStorageSync("cityId") || that.data.cityId
    }).then(res => {
      if (res.result) {
        that.setData({
          cityNumber: res.body.cityInfo,
          phoneNumber: res.body.customerManager,
        })
      }
    })
    // 是否是新人
    api.get_cart({
      cityId: wx.getStorageSync("cityId"),
      userId: wx.getStorageSync("openId"),
      page: {}
    }).then(res => {
      if(res.result){
        this.setData({
          isNewcomer:res.data.body && res.data.body.isNewcomer,
        })
        // 1是新人
        if (this.data.newType == "new") {
          if (res.data.body.isNewcomer != 1) {
            this.setData({
              isBindtap: false
            })
          }
        }
      }
    })
    //商品详情
    api.goodsDetails({
      cityId: wx.getStorageSync('cityId') || that.data.cityId,
      id: that.data.id,
      userId: wx.getStorageSync('openId') || that.data.userId,
    }).then(res => {
      if (res.result == true) {
        // 秒杀计时器
        let {
          shopId,
          goodsId
        } = that.data;
        let goodsList = res.object.goodsDetailsEntityList
        var swiper = []
        var detail = []

        if (shopId && shopId != "undefined") {
          //从多规格进来的
          let needIndex = goodsList.findIndex((v, i) => v.id == goodsId)
          if (res.body.goodsStock.length > 0) {
            let allNum = Math.floor(res.body.goodsStock[0].amount / goodsList[needIndex].spec)
            that.setData({
              allNum,
              goodsStock: res.body.goodsStock[0].amount,
              index: needIndex
              // goodsPic: res.object.goodsPic
            })
          }
          if (that.data.newType != "new") {
            if (goodsList[needIndex].activitySeckillId != null) { //有限时秒杀
              that.setData({
                isSeckill: false
              })
              if (goodsList[needIndex].seckillEndDate > Date.now()) { //计时器
                this.startTimer(goodsList[needIndex].seckillEndDate);
              }
            }
          }
          // 新人价格
          if (that.data.newType == "new" && that.data.isNewcomer != 1) {
            this.setData({
              isBindtap: false
            })
          }
          // vip
          if (that.data.newType == "vip") {
            if (wx.getStorageSync("vipFlag") == 0) {
              this.setData({
                isBindtap: false
              })
            }
          }
          that.setData({
            goodsId,
          })
        } else {
          goodsList.forEach((v, i) => {
            if (v.flag == 1) {

              // 库存数量
              if (res.body.goodsStock.length > 0) {
                let allNum = Math.floor(res.body.goodsStock[0].amount / v.spec)
                that.setData({
                  allNum,
                  goodsStock: res.body.goodsStock[0].amount
                })
              }
              that.setData({
                goodsId: v.id,
                index: i,
              })
              if (that.data.newType != "new") {
                //有限时秒杀
                if (v.activitySeckillId != null) {
                  that.setData({
                    isSeckill: false
                  })
                  if (v.seckillEndDate > Date.now()) { //计时器
                    this.startTimer(v.seckillEndDate);
                  }
                }
              }
              // vip
              if (that.data.newType == "vip") {
                if (wx.getStorageSync("vipFlag") != 1) {
                  this.setData({
                    isBindtap: false
                  })
                }
              }
            }
          })
        }
        if (res.data != 9999) {
          that.setData({
            collect: true //隐藏
          })
        }
        res.object.goodsPictureEntityList.forEach(function (value, index, array) {
          if (value.useType == 1) {
            if (value.url == null) {

            } else {
              swiper.push(value.url)
            }

          } else if (value.useType == 2) {
            if (value.url == null) {

            } else {
              detail.push(value.url)
            }
          }
        });

        let goodsRecommend = res.body.goodsRecommend
        if (wx.getStorageSync('type') == "2") {
          goodsRecommend.forEach(v => {
            v.detailSalesPrice = v.detailPersonalPrice || 0
            v.detailSalesPriceVip = v.detailPersonalPriceVip || 0
          })
        }

        if (wx.getStorageSync('type') == "2") {
          res.object.goodsDetailsEntityList.forEach(v => {
            api.roleSwitch(v)
          })
        }

        that.setData({
          swiperImage: swiper,
          detailImage: detail,
          goodsPic: swiper[0],
          shopNumber: res.body.getSum,
          num: goodsList,
          goodsMess: res.object,
          goodsRecommend: res.body.goodsRecommend,
          masking: '',
          fenid: res.object.userInfoEntity.id

        })
      }
    })
  },
  // 购物车加减数量
  handleItemNumEdit(e) {
    let that = this;
    // 访问接口更新数据
    // TODO 获取userId/cityId
    let index1 = e.currentTarget.dataset.index
    let num = that.data.num;
    let operation = e.currentTarget.dataset.operation;
    let cityId = wx.getStorageSync('cityId')
    let userInfoId = wx.getStorageSync('openId')
    let goodsName = that.data.goodsMess.name
    let goodsDetailsId = that.data.goodsId
    let price = that.data.goodsMess.goodsDetailsEntityList[index1].price
    let totalPrice = that.data.goodsMess.goodsDetailsEntityList[index1].priceVip
    // 起送数量
    let startNum = Number(that.data.goodsMess.goodsDetailsEntityList[index1].startNum)
    let allNum = that.data.allNum
    if (operation < 0) {
      //减号
      if (that.data.num[index1].amount == startNum) {
        that.data.num[index1].amount = 0;
      }
    }

    let new_amount = that.data.num[index1].amount + operation >= 0 ? that.data.num[index1].amount + operation : 0;
    // 价格    
    if (that.data.newType != "new") {
      if (that.data.goodsMess.goodsDetailsEntityList[index1].activitySeckillId == null) {
        if (wx.getStorageSync("vipFlag") == 1) {
          price = that.data.goodsMess.goodsDetailsEntityList[index1].salesPriceVip
          // totalPrice = price * new_amount
        } else {
          price = that.data.goodsMess.goodsDetailsEntityList[index1].salesPrice
          // totalPrice = price * new_amount
        }
      } else {
        price = that.data.goodsMess.goodsDetailsEntityList[index1].seckillPrice
        // totalPrice = price * new_amount
      }
    } else {
      price = that.data.goodsMess.goodsDetailsEntityList[index1].rookiePrice
    }
    totalPrice = price * new_amount
    if (new_amount >= 0) {
      api.set_amount({
        cityId,
        userInfoId,
        goodsName,
        goodsDetailsId,
        amount: new_amount,
        price,
        totalPrice
      }).then(res => {
        if (res.result) {
          num[index1].amount = new_amount
          that.setData({
            shopNumber: res.data,
            num
          })

        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none'
          })
        }
      })
    }
  },
  goShopping() {
    // wx.navigateTo({
    //   url: '/pages/gwc2/gwc',
    // })
    wx.switchTab({
      url: '/pages/gwc/gwc'
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    let userId = wx.getStorageSync("openId")
    let cityId = wx.getStorageSync("cityId")
    // let {goodsDetailsEntityList,goodsPictureEntityList}=this.data.goodsMess
    // let goodmess=JSON.stringify({goodsDetailsEntityList,goodsPictureEntityList})
    // let  goodmess =JSON.stringify(this.data.goodsMess) 
    console.log('id=' + this.data.id + '&userId=' + userId + '&cityId=' + cityId + '&fromShare=true' + '&fenid=' + this.data.fenid);
    return {
      title: "京天鲜生, 生鲜管家",
      path: '/pages/detail/detail?id=' + this.data.id + '&userId=' + userId + '&cityId=' + cityId + '&fromShare=true' + '&fenid=' + this.data.fenid,
      imageUrl: this.data.shareImg,
    }
  },
  addCollection: function () {
    let that = this
    api.insertSelective({
      cityId: wx.getStorageSync("cityId"),
      createid: wx.getStorageSync("openId"),
      goodsId: that.data.id
    }).then(res => {

      if (res.result) {
        if (res.data == 9999) {
          that.setData({
            collect: false
          })
          wx.showToast({
            title: '添加成功',
            icon: 'success',
            duration: 2000
          })
        } else {
          that.setData({
            collect: true
          })
          wx.showToast({
            title: '取消成功',
            icon: 'success',
            duration: 2000
          })
        }
      }
    })
  },
  drawImage1() {
    let self = this;
    this.drawImage1 = new Wxml2Canvas({
      width: 340, // 宽， 以iphone6为基准，传具体数值，其他机型自动适配
      height: 210, // 高
      element: 'canvas2',
      background: '#f0f0f0',
      progress(percent) { },
      finish(url) {
        let imgs = self.data.imgs;
        imgs.push(url);

        self.setData({
          imgs,
          shareImg: url,
          isShare: true
        })
        wx.showShareMenu({})
      },
      error(res) { }
    });
    let data = {
      list: [{
        type: 'wxml',
        class: '.share__canvas2 .draw_canvas', // draw_canvas指定待绘制的元素
        limit: '.share__canvas2', // 限定绘制元素的范围，取指定元素与它的相对位置
        x: 0,
        y: 0
      }]
    }
    this.drawImage1.draw(data, this);
  },

  saveImage() {
    wx.saveImageToPhotosAlbum({
      filePath: this.data.imgs[0],
      success(res) {
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        })
      },
      fail() {
        wx.showToast({
          title: '保存失败',
          icon: 'none'
        })
      }
    })
  },
  bindload() {
    this.drawImage1()
  },
  //获取数量
  inputNum(e) {
    let that = this
    let index1 = e.currentTarget.dataset.index;
    let startNum = Number(that.data.goodsMess.goodsDetailsEntityList[index1].startNum)
    let vals = Number(e.detail.value)
    if (e.detail.value == "" || e.detail.value == 0 || e.detail.value < startNum) {
      that.setData({
        inputNum: that.data.num[index1].amount
      })
    } else {
      that.setData({
        inputNum: vals
      })
    }
  },
  //失去焦点
  bindconfirm(e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    // 起送数量
    let startNum = Number(that.data.goodsMess.goodsDetailsEntityList[index].startNum)
    if (that.data.inputNum >= startNum) {
      if (that.data.inputNum == "") { } else {
        let num = that.data.num; //数量数组
        let goodsDetailsId = that.data.goodsId
        let goLists = that.data.goodsMess.goodsDetailsEntityList[index]
        // let price =goLists.price
        // let totalPrice = goLists.priceVip
        let price, totalPrice
        let userInfoId = wx.getStorageSync("openId")
        let cityId = wx.getStorageSync("cityId")
        let goodsName = that.data.goodsMess.name
        let amount = that.data.inputNum
        if (that.data.newType != "new") {
          if (goLists.activitySeckillId == null) {
            if (wx.getStorageSync("vipFlag") == 1) {
              price = goLists.salesPriceVip
              // totalPrice = price * amount
            } else {
              price = goLists.salesPrice
              // totalPrice = price * amount
            }
          } else {
            price = goLists.seckillPrice
            // totalPrice = price * amount
          }
        } else {
          price = goLists.rookiePrice
        }
        totalPrice = price * amount
        api.set_amount({
          cityId,
          userInfoId,
          goodsName,
          goodsDetailsId,
          amount,
          price,
          totalPrice
        }).then(res => {
          if (res.result) {
            num[index].amount = that.data.inputNum;
            that.setData({
              num,
              shopNumber: res.data
            });
          } else {
            wx.showToast({
              title: res.msg,
              icon: 'none'
            })
            num[index].amount;
            that.setData({
              num
            });
          }

        })
      }
    } else {
      if (that.data.inputNum != "") {
        wx.showToast({
          title: '请输入最小起送数量' + startNum,
          icon: 'none'
        })
      }

    }
  },
  // 组件中数据刷新
  uploadGoodsRecommend: function (e) { },
})